package com.db.test;

import cn.hutool.core.util.StrUtil;
import com.kingstar.jdbc.JdbcUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 测试不同线程下每个线程生成key不同并发写库
 *
 * @author dx
 */
public class MergeTask implements Runnable {
    private static final Logger log = LoggerFactory.getLogger(MergeTask.class);

    private String mergeSql = "MERGE INTO MERGE_TEST USING DUAL ON (id=?) \n" +
            "      WHEN NOT MATCHED THEN \n" +
            "           INSERT (id,c1,c2,c3) VALUES (?,?,?,?) \n" +
            "      WHEN MATCHED THEN\n" +
            "           UPDATE SET c1 =?,c2=?,c3=?";


    @Override
    public void run() {
        executeBatchMerge();
    }


    private void executeBatchMerge() {
        String threadName = Thread.currentThread().getName();
        int beginNum = Integer.valueOf(StrUtil.subAfter(threadName, "-", true) + "000");
        Connection conn = null;
        PreparedStatement ps = null;

        try {
            conn = JdbcUtils.getConnection();
            conn.setAutoCommit(false);
            ps = conn.prepareStatement(mergeSql);
            int endNum = beginNum + 1000;
            for (int i = beginNum; i < endNum; i++) {
                ps.setObject(1, i);
                ps.setObject(2, i);
                ps.setObject(3, i);
                ps.setObject(4, i);
                ps.setObject(5, i);
                ps.setObject(6, i);
                ps.setObject(7, i);
                ps.setObject(8, i);
                ps.addBatch();
            }
            ps.executeBatch();
            conn.commit();
            log.info("Thread [{}] merge execute success", threadName);

        } catch (Exception e) {
            try {
                if (conn != null) {
                    conn.rollback();
                }
            } catch (SQLException ex) {
                log.error("conn rollback error", ex);
            }
            log.error("Thread [{}] merge execute failed,message[{}]", threadName, e.getMessage(), e);


        } finally {
            JdbcUtils.close(ps, conn);
        }

    }

}
